import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:meco/common/index.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:path/path.dart' as path;
import 'package:meco/views/share/share/controller.dart';
import 'package:meco/views/me/me/controller.dart';
import 'package:path_provider/path_provider.dart' as path_provider;

class UploadController extends GetxController {
  UploadController();

  // 状态变量
  final Rx<File?> selectedImage = Rx<File?>(null);
  final Rx<AssetEntity?> selectedAsset = Rx<AssetEntity?>(null);
  final TextEditingController introductionController = TextEditingController();

  // 是否跳过烧制阶段
  final RxBool isSkipped = true.obs;

  // 陶瓷作品ID（如果从firing页面进入）
  final int? ceramicId = Get.arguments?['ceramic_id'];

  // 初始化数据
  _initData() {
    // 如果有传入参数，设置跳过标志
    if (Get.arguments != null) {
      isSkipped.value = Get.arguments['is_skipped'] ?? true;
    }

    update(["upload"]);
  }

  // 选择图片
  Future<void> pickImage() async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          specialPickerType: SpecialPickerType.noPreview,
        ),
      );

      if (result != null && result.isNotEmpty) {
        selectedAsset.value = result.first;
        final file = await result.first.file;
        if (file != null) {
          selectedImage.value = file;
          update(["upload"]);
        }
      }
    } catch (e) {
      EasyLoading.showError('选择图片失败: $e');
    }
  }

  // 提交发布
  Future<void> submitRelease() async {
    try {
      if (selectedImage.value == null) {
        EasyLoading.showInfo('Please select an image');
        return;
      }

      EasyLoading.show(status: 'Uploading...');

      // 获取用户ID
      final userService = Get.find<UserService>();
      final userId = userService.currentUser.value?.id;

      if (userId == null) {
        EasyLoading.dismiss();
        EasyLoading.showError('User not logged in');
        return;
      }

      // 处理陶瓷作品数据
      if (ceramicId != null) {
        // 如果从firing页面进入，更新现有陶瓷作品
        await _updateExistingCeramic(ceramicId!);
      } else {
        // 否则创建新陶瓷作品
        await _createNewCeramic(userId);
      }

      // 标记陶瓷作品为已完成状态，防止再次进入烧制页面显示旧数据
      if (ceramicId != null) {
        await _markCeramicAsComplete(ceramicId!);
      }

      // 刷新share页面的数据
      _refreshSharePage();

      // 刷新me页面的数据
      _refreshMePage();

      EasyLoading.dismiss();
      EasyLoading.showSuccess('Release successful!');

      // 返回到首页
      Get.until((route) => route.settings.name == Routes.main);
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError('Release failed: $e');
    }
  }

  // 刷新Share页面
  void _refreshSharePage() {
    // 如果ShareController已注册，重新加载它
    if (Get.isRegistered<ShareController>()) {
      // 获取当前的ShareController实例
      final shareController = Get.find<ShareController>();

      // 重新初始化数据
      shareController.onReady();
    }
  }

  // 刷新Me页面
  void _refreshMePage() {
    // 如果MeController已注册，重新加载它
    if (Get.isRegistered<MeController>()) {
      // 获取当前的MeController实例
      final meController = Get.find<MeController>();

      // 强制刷新数据
      meController.forceRefresh();
    }
  }

  // 标记陶瓷作品为已完成状态
  Future<void> _markCeramicAsComplete(int ceramicId) async {
    try {
      final ceramicRepository = CeramicRepository();
      final ceramic = await ceramicRepository.getCeramicById(ceramicId);

      if (ceramic != null) {
        // 添加标记，表示此陶瓷作品已完成上传，不应再被烧制页面加载
        final updatedCeramic = ceramic.copyWith(
          isCompleted: true,
          updatedAt: DateTime.now(),
        );

        await ceramicRepository.updateCeramic(updatedCeramic);
      }
    } catch (e) {
      print('标记陶瓷作品完成状态失败: $e');
    }
  }

  // 上传图片并获取URL
  Future<String> _uploadImage(File imageFile) async {
    try {
      // 在实际的应用中，这里应该将图片上传到服务器
      // 但在本地应用中，我们将图片复制到应用的文档目录

      // 获取应用文档目录
      final appDocDir = await path_provider.getApplicationDocumentsDirectory();
      final imagesDir = Directory('${appDocDir.path}/ceramic_images');

      // 确保目录存在
      if (!await imagesDir.exists()) {
        await imagesDir.create(recursive: true);
      }

      // 生成唯一文件名
      final fileName =
          '${DateTime.now().millisecondsSinceEpoch}_${path.basename(imageFile.path)}';
      final localPath = '${imagesDir.path}/$fileName';

      // 复制图片到应用文档目录
      final newFile = await imageFile.copy(localPath);

      // 返回图片的本地路径
      return newFile.path;
    } catch (e) {
      print('图片保存失败: $e');
      throw Exception('图片上传失败: $e');
    }
  }

  // 更新现有陶瓷作品
  Future<void> _updateExistingCeramic(int ceramicId) async {
    try {
      final ceramicRepository = CeramicRepository();

      // 获取现有陶瓷作品
      final ceramic = await ceramicRepository.getCeramicById(ceramicId);

      if (ceramic == null) {
        throw Exception('未找到陶瓷作品');
      }

      // 上传图片并获取URL
      final imageUrl = await _uploadImage(selectedImage.value!);

      // 更新陶瓷作品
      final updatedCeramic = ceramic.copyWith(
        title: introductionController.text,
        description: introductionController.text,
        imageUrl: imageUrl,
        updatedAt: DateTime.now(),
      );

      await ceramicRepository.updateCeramic(updatedCeramic);
    } catch (e) {
      throw Exception('更新陶瓷作品失败: $e');
    }
  }

  // 创建新陶瓷作品
  Future<void> _createNewCeramic(int userId) async {
    try {
      final ceramicRepository = CeramicRepository();
      final ceramicStageRepository = CeramicStageRepository();

      final now = DateTime.now();

      // 上传图片并获取URL
      final imageUrl = await _uploadImage(selectedImage.value!);

      // 创建新陶瓷作品
      final ceramic = Ceramic(
        userId: userId,
        title: introductionController.text,
        description: introductionController.text,
        imageUrl: imageUrl,
        isSkipped: isSkipped.value,
        isCompleted: true, // 新创建的直接标记为已完成
        createdAt: now,
        updatedAt: now,
      );

      // 保存到数据库
      final ceramicId = await ceramicRepository.addCeramic(ceramic);

      // 如果没有跳过烧制阶段，创建所有阶段
      if (!isSkipped.value) {
        await ceramicStageRepository.createStagesForCeramic(ceramicId);
      }
    } catch (e) {
      throw Exception('创建陶瓷作品失败: $e');
    }
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  @override
  void onClose() {
    introductionController.dispose();
    super.onClose();
  }
}
